(function () {
    'use strict';

    angular
        .module('logcenterApp')
        .controller('alertSubController', alertSubController);
    alertSubController.$inject = ['$scope','$filter', 'toaster', 'AlertSubService', 'searchService', 'AlertTypeService','AlertUserService', 'logAlertMsgEnabled'];

    function alertSubController($scope,$filter, toaster, AlertSub, searchService, AlertTypeService,AlertUserService, logAlertMsgEnabled) {
        var notify = function (type, title, message) {
            toaster.pop(type, title, message);
        };

        $scope.condition = {
            userId: '',
            alertId: null,
            partitionId: '',
            moduleName: '',
            msgType: null
        };
        $scope.editable = {
            mode: "popup",
            template: kendo.template($("#gridEditor").html())
        };

        logAlertMsgEnabled ? $scope.sendTypeData = [
            {value: '0', text: '邮件'},
                {value: '1', text: '短信'},
                {value: '2', text: '邮件&短信'}
            ] : $scope.sendTypeData = [
            {value: '0', text: '邮件'}
        ];

        searchService.getPartition({cname: null, fname: null, ename: null}).then(function (resp) {
            $scope.partitionData = resp.data;
        }, function (error) {
            notify('error', '失败', '查询分区失败!' + error);
        });

        $scope.partitionHeaderTmp = kendo.template($("#partition-header-template").html());
        $scope.partitionTmp = kendo.template($("#partition-template").html());

        AlertTypeService.query({}).then(function (resp) {
            $scope.alertTypeData = resp;
        }, function (error) {
            notify('error', '失败', '查询报警类型失败!' + error);
        });

        AlertUserService.query({}).then(function (resp) {
            $scope.userData=resp;
        },function (error) {
            notify('error', '失败', '查询用户信息失败!' + error);
        });
        $scope.alertTypeHeaderTmp = kendo.template($("#alertType-header-template").html());
        $scope.alertTypeTmp = kendo.template($("#alertType-template").html());


        $scope.userHeaderTmp = kendo.template($("#user-header-template").html());
        $scope.userTmp = kendo.template($("#user-template").html());

        $scope.selectUser=function (dataItem,e) {
            dataItem.dirty=true;
            $scope.currentModel.set('userName',e.sender.dataItem().userName);
            //console.log(e.sender.value());
        };

        $scope._initPage = true;
        $scope.toolbar = [
            "create",
            {
                template: '<kendo-button ng-click="update($event)"><span class="k-icon k-i-edit"></span>编辑</kendo-button>'
            },
            {
                template: '<kendo-button ng-click="destroy($event)"><span class="k-icon k-i-delete"></span>删除</kendo-button>'
            }

        ];
        $scope.pageable = {
            refresh: true,
            pageSizes: true,
            numeric: false,
            input: true
        };
        $scope.Model = kendo.data.Model.define({
            id: "id",
            fields: {
                id: {type: "number", nullable: true, hidden: true, editable: false},
                userId: {type: "string", validation: {required: true}},
                alertId: {type: "string", validation: {required: true}},
                partitionId: {type: "string", validation: {required: true}},
                moduleName: {type: "string", validation: {required: true}},
                msgType: {type: "number", validation: {required: true}},
                recCreateTime: {type: "string"},
                recCreator: {type: "string"}

            }
        });
        $scope.columns = [
            {
                field: "userId", title: "工号", width: 150
            },
            {
               field:"userName",title:"姓名",width:150
            },
            {
                field: "alertId", title: "报警类型", width: 150,
                template: function (dataItem) {
                    var desc = '';
                    if ($scope.alertTypeData) {
                        angular.forEach($scope.alertTypeData, function (item, i) {
                            if (item.alertId == dataItem.alertId) {
                                desc = item.alertDesc;
                            }
                        });
                    }
                    return desc == "" ? dataItem.alertId : desc;
                }
            },
            {
                field: "partitionId", title: "分区", width: 150
            },
            {
                field: "moduleName", title: "功能名", width: 150
            },
            {
                field: "msgType", title: "发送方式", width: 150,
                template: function (dataItem) {
                    var desc = '';
                    if ($scope.sendTypeData) {
                        angular.forEach($scope.sendTypeData, function (item, i) {
                            if (item.value == dataItem.msgType) {
                                desc = item.text;
                            }
                        });
                    }
                    return desc == "" ? dataItem.msgType : desc;
                }
            },
            {
                field: "recCreateTime", title: "操作时间", width: 150
            },
            {
                field: "recCreator", title: "操作人", width: 150
            }
        ];

        $scope.dataSource = new kendo.data.DataSource({
            autoBind: false,
            transport: {
                read: function (e) {
                    AlertSub.query($scope.condition).then(function (response) {
                        e.success(response);
                    }, function (error) {
                        e.error(error);
                        notify('error', '失败', '查询失败' + error);
                    });
                },
                create: function (e) {
                    AlertSub.save(e.data.models[0]).then(function (response) {
                        e.success(response);
                        notify('success', '成功', '新增成功！');
                    }, function (error) {
                        e.error(error);
                        notify('error', '失败', '新增失败' + error);
                    });
                },
                update: function (e) {
                    AlertSub.save(e.data.models[0]).then(function (response) {
                        e.success(response);
                        notify('success', '成功', '修改成功！');
                    }, function (error) {
                        e.error(error);
                        notify('error', '失败', '修改失败' + error);
                    });
                },
                destroy: function (e) {
                    AlertSub.destroy(e.data.models[0]).then(function (response) {
                        e.success(response);
                        notify('success', '成功', '删除成功！');
                    }, function (error) {
                        e.error(error);
                        notify('error', '失败', '删除失败' + error);
                    });
                },

                parameterMap: function (options, operation) {
                    if (operation !== "read" && options.models) {
                        return {models: kendo.stringify(options.models)};
                    }
                }
            },
            requestStart: function (e) {
                if ($scope._initPage) {
                    e.preventDefault();
                }
            },
            batch: true,
            pageSize: 15,
            schema: {
                model: $scope.Model
            }
        });

        $scope.query = function () {
            $scope._initPage = false;
            $scope.grid.dataSource.read();
        };

        $scope.update = function (e) {
            var selected = $scope.grid.select();
            if (selected.length == 0) {
                //alert('No record selected')
                notify('waring', '提示', '请先选择一行！');
            } else {
                $scope.grid.editRow(selected);
            }
        };
        $scope.destroy = function (e) {
            var selected = $scope.grid.select();
            if (selected.length == 0) {
                //alert('No record selected')
                notify('waring', '提示', '请先选择一行！');
            } else {
                $scope.grid.removeRow(selected);
            }
        };
        $scope.gridRowEdit = function (e) {
            var time= $filter('date')(new Date(), 'yyyyMMddHHmmss');
            e.model.set('recCreateTime',time);
            e.model.set('recCreator','admin');
            $scope.currentModel=e.model;
            /*if (!e.model.isNew()) {
            }

            entity.recCreateTime =time;
            entity.recCreator ='admin';*/
        };
    }
})();
